<?php

Yii::import('application.models._base.BaseFirms');

class Firms extends BaseFirms {
    public $oldData;

	public static function model($className=__CLASS__) {
		return parent::model($className);
	}
    
    public function afterFind() {
        $this->oldData = clone $this;
        return parent::afterFind();     
    }    
    
    
    
	public function beforeSave() {
    if ($this->isNewRecord) {
      if ($this->hasAttribute('crdate')) {
          $this->crdate = time();
      }
    }	 
    if ($this->hasAttribute('slug')) {
      if ('' == $this->slug) $this->slug = $this->makeSlug($this->title);    
    }

    if ($this->modifiedAddrData() && !in_array($this->firm_tmpl_id, Yii::app()->params['default_free_firm_tmpl_ids'])) {
      $response = Controller::getYandexGeo($this);
      if ('success' == $response['r']) {
        $this->longitude = $response['longitude'];
        $this->latitude = $response['latitude'];
      }
    }
    return parent::beforeSave();
	}	    
    
	
	
	
    
    protected function modifiedAddrData() {
        $data = false;
        if (!$this->oldData) {
            return true;
        }
        
        if ($this->oldData->country_id !== $this->country_id) {
            $data = true;
        }
        if ($this->oldData->region_id !== $this->region_id) {
            $data = true;
        }
        if ($this->oldData->city_id !== $this->city_id) {
            $data = true;
        }        
        if ($this->oldData->address !== $this->address) {
            $data = true;
        }        
        return $data;
    }
	
	
	
	private function increaseForAll() {
		Yii::app()->db->createCommand("UPDATE regions SET quantity = quantity + 1 WHERE id = ".$this->region_id)->query();
		Yii::app()->db->createCommand("UPDATE cities SET quantity = quantity + 1 WHERE id = ".$this->city_id)->query();
		
		Yii::app()->db->createCommand("UPDATE rubrics SET quantity = quantity + 1 WHERE id = ".$this->rubric_id)->query();
		Yii::app()->db->createCommand("UPDATE categories SET quantity = quantity + 1 WHERE id = ".$this->category_id)->query();
	}
	
	private function decreaseForAll() {
		Yii::app()->db->createCommand("UPDATE regions SET quantity = quantity - 1 WHERE id = ".$this->region_id)->query();
		Yii::app()->db->createCommand("UPDATE cities SET quantity = quantity - 1 WHERE id = ".$this->city_id)->query();
		
		Yii::app()->db->createCommand("UPDATE rubrics SET quantity = quantity - 1 WHERE id = ".$this->rubric_id)->query();
		Yii::app()->db->createCommand("UPDATE categories SET quantity = quantity - 1 WHERE id = ".$this->category_id)->query();
	}
	
	protected function afterSave() {
		parent::afterSave();
		if ($this->isNewRecord) {
			$this->increaseForAll();
		} else {
			if (!$this->oldData) {
				return false;
			}
			
			if ($this->oldData->deleted != $this->deleted) {
				if (0 == $this->oldData->deleted && 1 == $this->deleted) {
					$this->decreaseForAll();
				} elseif(1 == $this->oldData->deleted && 0 == $this->deleted) {
					$this->increaseForAll();
				}
			} elseif ($this->oldData->hidden != $this->hidden) {
				if (0 == $this->oldData->hidden && 1 == $this->hidden) {
					$this->decreaseForAll();
				} elseif(1 == $this->oldData->hidden && 0 == $this->hidden) {
					$this->increaseForAll();
				}
			} else {
					if ($this->oldData->region_id !== $this->region_id) {
						Yii::app()->db->createCommand("UPDATE regions SET quantity = quantity - 1 WHERE id = ".$this->oldData->region_id)->query();
						Yii::app()->db->createCommand("UPDATE regions SET quantity = quantity + 1 WHERE id = ".$this->region_id)->query();
					}
					if ($this->oldData->city_id !== $this->city_id) {
						Yii::app()->db->createCommand("UPDATE cities SET quantity = quantity - 1 WHERE id = ".$this->oldData->city_id)->query();
						Yii::app()->db->createCommand("UPDATE cities SET quantity = quantity + 1 WHERE id = ".$this->city_id)->query();
					}    

					if ($this->oldData->rubric_id !== $this->rubric_id) {
						Yii::app()->db->createCommand("UPDATE rubrics SET quantity = quantity - 1 WHERE id = ".$this->oldData->rubric_id)->query();
						Yii::app()->db->createCommand("UPDATE rubrics SET quantity = quantity + 1 WHERE id = ".$this->rubric_id)->query();
					}		
						
					if ($this->oldData->category_id !== $this->category_id) {
						Yii::app()->db->createCommand("UPDATE categories SET quantity = quantity - 1 WHERE id = ".$this->oldData->category_id)->query();
						Yii::app()->db->createCommand("UPDATE categories SET quantity = quantity + 1 WHERE id = ".$this->category_id)->query();		
					}				
			}
		}
	}	
	
	
	
    public function scopes($data = null) {
        return array(
            'visible'=>array(
                'condition'=>'t.hidden=0',
            ),
			'hidden' =>array(
                'condition'=>'t.hidden=1',
			),
            'actual' => array(
                'condition'=>'t.hidden=0 AND t.deleted = 0 AND t.active = 1',
			),
            'by_id_desc'=>array(
                'order'=>'id DESC',
            ),
            'by_id_asc'=>array(
                'order'=>'id ASC',
            ),
		);
    } 	
    
    public function latest($data) {
        $this->getDbCriteria()->mergeWith(array(
            'order' => 't.id DESC',
            'limit' => intval($data),
        ));
        return $this;
    }  	
    
    
    public function random($data) {
        $this->getDbCriteria()->mergeWith(array(
            'order' => 'RAND()',
            'limit' => $data,
        ));
        return $this;
    }    
    
    public function firm_tmpl($data) {
        $this->getDbCriteria()->mergeWith(array(
            'condition' => 'firm_tmpl_id = '.$data,
        ));
        return $this;
    }     
    
    
    
	public function fast_search() {
		$criteria = new CDbCriteria;

//		$criteria->compare('crdate', $this->crdate);
		$criteria->compare('hidden', 0);
		$criteria->compare('active', 1);
        
        $criteria->compare('service_type', $this->service_type);
		$criteria->compare('rubric_id', $this->rubric_id);
		$criteria->compare('category_id', $this->category_id);
		$criteria->compare('country_id', $this->country_id);
		$criteria->compare('region_id', $this->region_id);
		$criteria->compare('city_id', $this->city_id);
        
        
//		$criteria->compare('start_date', $this->start_date);
//		$criteria->compare('end_date', $this->end_date);

		return new CActiveDataProvider($this, array(
			'criteria' => $criteria,
		));
	}    
    
    
}